package com.example.order.service.impl;

/**
 * @author FanFu
 * @version 1.0
 * @date 2025/11/8 20:23
 */
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.order.entity.Order;
import com.example.order.mapper.OrderMapper;
import com.example.order.service.OrderService;
import com.example.order.service.kafka.OrderKafkaProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ORDER_CACHE_PREFIX = "order:";
    private static final String USER_ORDERS_CACHE_PREFIX = "user:orders:";


    @Autowired
    private OrderKafkaProducer orderKafkaProducer;

    // ... 其他代码保持不变 ...

    @Override
    @Transactional
    public boolean save(Order order) {
        boolean result = super.save(order);
        if (result && order.getId() != null) {
            // 发送订单创建消息到Kafka
            orderKafkaProducer.sendOrderCreateMessage(order);
            // 清除相关缓存
            clearOrderCache(order.getId(), order.getUserId());
        }
        return result;
    }
    /**
     * 清除订单相关缓存
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     */
    private void clearOrderCache(Long orderId, Long userId) {
        if (orderId != null) {
            String orderCacheKey = ORDER_CACHE_PREFIX + orderId;
            redisTemplate.delete(orderCacheKey);
        }
        if (userId != null) {
            String userOrdersCacheKey = USER_ORDERS_CACHE_PREFIX + userId;
            redisTemplate.delete(userOrdersCacheKey);
        }
    }


    @Override
    public Order getOrderById(Long id) {
        if (id == null) {
            return null;
        }

        String cacheKey = ORDER_CACHE_PREFIX + id;

        // 先从Redis查询
        Order order = (Order) redisTemplate.opsForValue().get(cacheKey);
        if (order != null) {
            return order;
        }

        // Redis中没有，查询数据库
        order = this.getById(id);
        if (order != null) {
            redisTemplate.opsForValue().set(cacheKey, order, 30, TimeUnit.MINUTES);
        }

        return order;
    }
    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        if (userId == null) {
            return null;
        }

        String cacheKey = USER_ORDERS_CACHE_PREFIX + userId;

        // 先从Redis查询
        List<Order> orders = (List<Order>) redisTemplate.opsForValue().get(cacheKey);
        if (orders != null) {
            return orders;
        }

        // Redis中没有，查询数据库
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");
        orders = this.list(queryWrapper);

        if (orders != null && !orders.isEmpty()) {
            redisTemplate.opsForValue().set(cacheKey, orders, 10, TimeUnit.MINUTES);
        }

        return orders;
    }
}